package com.zs.studentmanager.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.zs.studentmanager.entity.domain.User;

import java.util.HashMap;

/**
 * @author: 周小白
 * @date: 2024-01-19 20:33
 * @description: JWT工具类
 **/
public class JwtUtil {


    /**
     * 创建token
     * @param user 用户信息
     * @return token
     */
    public static String createToken(User user) {
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.MINUTE, 120);
        HashMap<String, Object> payload = new HashMap<>();

        // 生成签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 生成过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        // 载荷
        payload.put("userName", user.getUserName());
        payload.put("userId", user.getId());
        String key = "white-zhou";

        // 生成token
        return JWTUtil.createToken(payload, key.getBytes());
    }



    /**
     * 解析token
     * @param token token
     * @return 用户信息
     */
    public static long parseToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);

        String userId = jwt.getPayload("userId").toString();

        return Long.parseLong(userId);
    }
}
